﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using COMOSOFT.OrderBusiness.Forms;
using System.Data.SqlClient;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using System.IO;
using COMOSOFT.Class;
using COMOSOFT.OrderBusiness;
using COMOSOFT.MatarialManagement.Forms;
using COMOSOFT.JobManagement.Froms;
using COMOSOFT.WareHouse_Management.Forms;
using COMOSOFT.HumanResource.Forms;
using COMOSOFT.Production.Forms;
using COMOSOFT.ShippingManagement.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraNavBar;
using DevExpress.XtraBars.Alerter;
using DevExpress.XtraTabbedMdi;
using System.Net.Mail;
using System.Deployment.Application;
using DevExpress.LookAndFeel;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Localization;
using DevExpress.XtraReports.UI;
using Merchandising_Software.TrimNew.report;

namespace COMOSOFT.Main
{
    public partial class FrmMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {        
        UpdateCheckInfo info = null;
        ApplicationDeployment ad = null;
        ClassShare cls = new ClassShare("FrmMain");

        //Job
        FrmJobManagement frJobM = null;
        FrmJobGeneral frJobGr = null;
        FrmJobStatistic frJobStatistic = null;
        FrmJobView frJobView = null; 
 
        //HR
        FrmEmployeeList frEList = null;

        //Order
        int CMID;
        object Cus;
        TabGeneralView frGV = null;
        FrmFactoryPurchaseMaster frFPM = null;
        FrmStyleDetails frSD = null;
        TabOrderDetails frOrderDetails = null;
        FrmCostingDetails frCostD = null;
        FrmCostingGaneral frCGV = null;

        //Material/Accessories
        FrmMAGeneralView frMAGV = null;
        FrmMALibrary frMALib = null;
        FrmBAGaneralView frBaGV = null;
        FrmBookMA frBMA = null;
        FrmMaterial frMA = null;
        FrmAccessoriesView frAV = null;
        FrmConfirmCons frCFC = null;  
      
        //WareHouse
        bool bGV = false;
        FrmImportMA frImportMA = null;
        FrmExportMA frExMA = null;
        FrmStockGaneralView frSGV = null;
        FrmImportMAGaneral frIptMAGV = null;

        //Production
        FrmProductionPlanning frProPlan = null;
        FrmOrderInfo frOrderInfo = null;
        FrmProductionOutlinePlanningDaily frPOP = null;
        object obYear, obMonth, obOID, obSubIID, obSubFLID,obSuplier;
        int iYear;   

        //Delivery
        bool flag = true;
        FrmDeliveryGaneral frDGaneral = null;
        FrmDeliveryView frDView = null;
        FrmProductionInventory frInventory = null;   
    
        //Shipping
        int iSAID,iInvID;        
        FrmInvoice frmInv = null;
        FrmShipMent frmshipment = null;

        //Product Import
        FrmImportProduct frImptProduct = null;

        //*************************************
        bool IsRemember = false,IsInit=false;
       
       // DataTable dtbJob;       
        string _pages = null;        
        string Items=null;
        int JID,NewJobID=-1, Timejob=0,TimeAlert=0,TimeRequester=0,TimeNotAccept=0,TimeJobEx=0,TimeCheckUpdate=0;
        int RequestTime = 0,TimeSubmit=0;
        List<string> Pages = new List<string>();
        // 
        struct _Layout
        {
            public string formname;
            public string pagename;
            public string NavBarName;
        }
        List<_Layout> ListLayout = new List<_Layout>();
        //---------------
        public FrmMain()
        {            
            InitializeComponent();           
            DevExpress.UserSkins.BonusSkins.Register();
            IsInit = true;
            IsRemember = ClassShare.IsRemember;            
            ClassShare.frmain = this;
            cls.CreateFolder();

            #region [Skin]
            SkinHelper.InitSkinGallery(ribbonGallery_Job);
            SkinHelper.InitSkinGallery(ribbonGallery_Orderskin);
            SkinHelper.InitSkinGallery(ribbonGallery_MASkin);
            SkinHelper.InitSkinGallery(ribbonGallery_WHSkin);
            SkinHelper.InitSkinGallery(ribbonGallery_PMSkin);            
            SkinHelper.InitSkinGallery(ribbonGallery_HR);
            SkinHelper.InitSkinGallery(ribbonGallery_Shippingskin); 
           //LoadSkin         
            
            #endregion

            #region [RememberAcount]
            if (File.Exists(ClassShare.lcSystem + @"\config.dat"))
               File.Delete(ClassShare.lcSystem + @"\config.dat");
            if (IsRemember == true)
            {
                FileStream stream = new FileStream(ClassShare.lcSystem + @"\config.dat", FileMode.Create);
                BinaryWriter binstr = new BinaryWriter(stream);
                binstr.Write(ClassShare.UserN);
                binstr.Write(ClassShare.Pass);
                binstr.Write(IsRemember);
                binstr.Close();
            }
            #endregion
        }

        #region[Caption NavBar]
        string strJobList = "Job List";
        string strEmp = "Employee List";
        string strCosting = "Costing Details";
        string strOrder = "Order General";
        string strPurchasing = "Purchasing View";
        string strMASource = "Material Library";
        string strMAList = "Material List";
        string strBlance = "Balancing";
        string strBook = "Booking";
        string strException = "Exception";
        string strIptMA = "Import Material";
        string strIptPro = "Import Product";
        string strEptMA = "Export Material";
        string strEptPro = "Export Product";
        string strStock = "Stock And Exception";
        string strProPlanning = "Production Planning";
        string strFollowUp = "Fallow Up";
        string strDePlanning = "Delivery Planning";
        string strShipping = "Shipping Advice";
        #endregion

        #region[Check Permission]
        private void CheckPermission()
        {
            if (ClassShare.Position == "Manager" || ClassShare.Position == "Leader" || ClassShare.Position == "Admin")
            {
                bnt_Statistic.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                bnt_JobGeneral.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                bnt_MAConfirmCons.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                ribbonPage_HR.Visible = true;
            }
        }
        #endregion

        #region [CheckTabPage on Ribbon]
        public void CheckTabPage()
        {
            try
            {
                DataTable dtb = cls.CheckEmployee(ClassShare.Usid);
                if (dtb.Rows.Count > 0)
                {
                    for (int n = 0; n < dtb.Rows.Count; n++)
                    {
                        string tabname = dtb.Rows[n][0].ToString();
                        int num = ribbon.Pages.Count;
                        for (int i = 0; i < num; i++)
                        {
                            if (Ribbon.Pages[i].Text == tabname)
                            {
                                Ribbon.Pages[i].Visible = true;
                            }
                        }                        
                    }
                }
                this.Text = Ribbon.SelectedPage.Text;
                CheckNavbarcontrol(Ribbon.SelectedPage.Text);
            }
            catch(Exception e)
            {
                XtraMessageBox.Show(e.Message);
            }
        }
        #endregion

        #region [Clear TabbedManager]
        private void ClearTabbed()
        {
            int numpage = xtraTabbedMdiManager_TabForm.Pages.Count;
            for (int i = 0; i < numpage; i++)
            {
                xtraTabbedMdiManager_TabForm.Pages[0].MdiChild.Close();
            }
        }
        #endregion

        #region[Ribbon CLick]
        private void ribbon_Click(object sender, EventArgs e)
        {
            try
            {
                string pagename = Ribbon.SelectedPage.Text;
                SelectPage(pagename);               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SelectPage(string pagename)
        {
            if (_pages != null && _pages != pagename)
            {
                this.Text = pagename;
                CheckNavbarcontrol(pagename);
                _pages = pagename;                        
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;                
            }
        }
        #endregion

        #region[Save Skin]
        private void ribbonGallery_Job_GalleryItemCheckedChanged(object sender, DevExpress.XtraBars.Ribbon.GalleryItemEventArgs e)
        {
            if (IsInit == false)
            {
                string skiname = e.Item.Caption.ToString();
                if (File.Exists(ClassShare.lcSystem + @"\Skin.dat"))
                    File.Delete(ClassShare.lcSystem + @"\Skin.dat");
                FileStream stream = new FileStream(ClassShare.lcSystem + @"\Skin.dat", FileMode.Create);
                BinaryWriter binstr = new BinaryWriter(stream);
                binstr.Write(skiname);
                binstr.Close();
            }
            IsInit = false;
        }
        #endregion

        #region [Form Load]
        private void FrmMain_Load(object sender, EventArgs e)
        {
            sp_ImportProductMenuTableAdapter.Fill(this.dataSet_Product.sp_ImportProductMenu);
            sp_SAMenuTableAdapter.Fill(this.dataSet_ShipMent.sp_SAMenu);
            sp_CostingMenuTableAdapter.Fill(this.dataSetOrderManagement.sp_CostingMenu);         
            sp_DeliveryMenuTableAdapter.Fill(this.dataSet_Delivery.sp_DeliveryMenu);            
            sp_ProductionPlanMenuTableAdapter.Fill(this.dataSet_Production.sp_ProductionPlanMenu);            
            sp_FollowMenuTableAdapter.Fill(this.dataSet_Production.sp_FollowMenu);
            sp_BalanceMenuTableAdapter.Fill(this.dataSetBalancing.sp_BalanceMenu);         
            sp_WHExportMenuTableAdapter.Fill(this.dataSet_WareHouse.sp_WHExportMenu);
            navBarControl_menu.NavigationPaneMaxVisibleGroups = 4;
            sp_MAIPMenuTableAdapter.Fill(dataSet_WareHouse.sp_MAIPMenu);
            barSystemInfo.Caption = DateTime.Now.ToString("dddd, MMMM-dd-yyyy") + " || User login: " + ClassShare.UserN + " - FullName: " + ClassShare.Usname + " - StaffNo: " + ClassShare.StaffNo + " || COMO Co.,Ltd";
            if (File.Exists(ClassShare.lcSystem + @"\Skin.dat"))
            {
                BinaryReader binrd = new BinaryReader(new FileStream(ClassShare.lcSystem + @"\Skin.dat", FileMode.Open));
                string skinname = binrd.ReadString();
                binrd.Close();
                UserLookAndFeel.Default.SetSkinStyle(skinname);
            }
            notifyIcon_comosoft.Text = "comosoft - " + ClassShare.Usname;
            this.sp_BookMAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BookMAMenu);
            this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
            this.employeeTableAdapter.Fill(dataSet_JobManagement.Employee, ClassShare.Usid);
            DataTable dtb = dataSet_JobManagement.Employee;
            if (dtb.Rows.Count > 0)
            {
                if (dtb.Rows[0]["Image"].ToString() != null && dtb.Rows[0]["Image"].ToString() != "")
                {
                    try
                    {
                        if (!File.Exists(ClassShare.lcSystem + dtb.Rows[0]["Image"].ToString()))
                            cls.Dowload(ClassShare.ftpSystem, ClassShare.lcSystem, dtb.Rows[0]["Image"].ToString());
                        byte[] Img = System.IO.File.ReadAllBytes(ClassShare.lcSystem + dtb.Rows[0]["Image"].ToString());
                        picture_Image.EditValue = Img;
                    }
                    catch
                    {
                    }
                }
            }
            //this.sp_JobMenuTableAdapter.Fill(this.dataSet_JobManagement.sp_JobMenu, ClassShare.Usid);
            this.sp_MALibraryMenuTableAdapter.Fill(this.dataSetMatarial1.sp_MALibraryMenu);
            this.sp_MAListMasterLoadTableAdapter.Fill(this.dataSetMatarial.sp_MAListMasterLoad);
            this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
            ribbonPageGroup_FtyPurChase.Visible = false;
            _pages = ribbon.SelectedPage.Text;
            //JobView
            frJobView = new FrmJobView();
            frJobView.Show();
            frJobView.MdiParent = this;
            frJobView.LoadData();
            //---------------------------
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            Savelayout(frJobView.Text, ribbon.SelectedPage.Text,strJobList);
        }
        #endregion

        //Order Business   
        #region[SelectedPage]
        public void SelectedPageGroup(string strNavBarCaption)
        {
            try
            {                
                switch (strNavBarCaption)
                {
                    //OrderDetails
                    case "Job List":
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Costing Details":
                        ribbonPageGroup_CostingDetails.Visible = true;                       
                        ribbonPageGroup_OrderDetails.Visible = false;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    case "Order General":
                        ribbonPageGroup_OrderDetails.Visible = true;                       
                        ribbonPageGroup_CostingDetails.Visible = false;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;                    
                    //-----------------
                    //Material
                    case "Material Library":
                        ribbonPageGroup_MALibrary.Visible = true;
                        ribbonPageGroup_Matarial.Visible = false;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = false;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    case "Material List":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible = true;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = false;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    case "Booking":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible = false;
                        ribbonPageGroup_Booking.Visible = true;
                        ribbonPageGroup_Balance.Visible = false;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    case "Balancing":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible = false;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = true;
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    //-----------------
                    //WareHouse
                    case "Import Material":
                        ribbonPageGroup_ImportMaterial.Visible = true;
                        ribbonPageGroup_ExportMaterial.Visible = false;
                        ribbonPageGroup_ImportProduct.Visible = false;
                        ribbonPageGroup_StockException.Visible = false;
                        break;
                    case "Export Material":
                        ribbonPageGroup_ImportMaterial.Visible = false;
                        ribbonPageGroup_ExportMaterial.Visible = true;
                        ribbonPageGroup_ImportProduct.Visible = false;
                        ribbonPageGroup_StockException.Visible = false;
                        break;
                    case "Import Product":
                        ribbonPageGroup_ImportMaterial.Visible = false;
                        ribbonPageGroup_ExportMaterial.Visible = false;
                        ribbonPageGroup_ImportProduct.Visible = true;
                        ribbonPageGroup_StockException.Visible = false;
                        break;
                    case "Stock And Exception":
                        ribbonPageGroup_ImportMaterial.Visible = false;
                        ribbonPageGroup_ExportMaterial.Visible = false;
                        ribbonPageGroup_ImportProduct.Visible = false;
                        ribbonPageGroup_StockException.Visible = true;
                        break;
                    //Production
                    case "Purchasing View":
                        ribbonPageGroup_PurchaseToFactory.Visible = true;
                        ribbonPageGroup_ProductionPlanning.Visible = false;
                        ribbonPageGroup_FollowUp.Visible = false;
                        ribbonPageGroup_DeliveryPlanning.Visible = false;   
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                        break;
                    case "Production Planning":
                        ribbonPageGroup_PurchaseToFactory.Visible = false;
                        ribbonPageGroup_ProductionPlanning.Visible = true;
                        ribbonPageGroup_FollowUp.Visible = false;
                        ribbonPageGroup_DeliveryPlanning.Visible = false;                        
                        break;
                    case "Follow Up":
                        ribbonPageGroup_PurchaseToFactory.Visible = false;
                        ribbonPageGroup_ProductionPlanning.Visible = false;
                        ribbonPageGroup_FollowUp.Visible = true;
                        ribbonPageGroup_DeliveryPlanning.Visible = false;                       
                        break;
                    case "Delivery Planning":
                        ribbonPageGroup_PurchaseToFactory.Visible = false;
                        ribbonPageGroup_ProductionPlanning.Visible = false;
                        ribbonPageGroup_FollowUp.Visible = false;
                        ribbonPageGroup_DeliveryPlanning.Visible = true;                       
                        break;
                    case "Shipping Advice":
                        break;
                    //------------------------------------
                    default:
                        break;
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database! Connect try again");
            }
        }
        #endregion

        #region [Refresh data]
        public void RefreshOrdermenu()
        {
            try
            {
                gridOrderMenu.DataSource = sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);
                grid_FtyPurMaster.DataSource = sp_FtyPurMasterLoadTableAdapter.Fill(dataSetOrderManagement.sp_FtyPurMasterLoad);
                frGV = ActiveMdiChild as TabGeneralView;
                frGV.RefreshData();             
            }
            catch
            {
                MessageBox.Show("Can't refresh! Please try again!");
            }
        }
        #endregion

        #region[Event Ribbon OrderDetails]
        private void OrderDetails_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "Add Order":
                        frOrderDetails = new TabOrderDetails(-1) { MdiParent = this, Text = "Add new Order" };
                        frOrderDetails.Show();
                        frOrderDetails.AddNew();  
                        frOrderDetails.LoadData();
                        Savelayout(frOrderDetails.Text, ribbon.SelectedPage.Text, strOrder);
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    break;
                case "Save":
                    if (frOrderDetails != null && !frOrderDetails.IsDisposed)
                    {
                        frOrderDetails.UpdateData("Update");
                        frOrderDetails.LoadData();
                        sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);
                        Savelayout(frOrderDetails.Text, ribbon.SelectedPage.Text, strOrder);
                    }
                    break;
                case "Delete":
                    if (frOrderDetails != null && !frOrderDetails.IsDisposed)
                    {
                        frOrderDetails.UpdateData("Delete");                       
                        sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);                        
                    }
                    break;
                case "Refresh":
                    if (frOrderDetails != null && !frOrderDetails.IsDisposed)
                        frOrderDetails.LoadData();
                    break;
                default :
                    if (frOrderDetails != null && !frOrderDetails.IsDisposed)
                    {
                        frOrderDetails.PreviewOrder();
                    }
                    break;
            }
        }
        #endregion        

        #region [Top data]
        public void TopData()
        {
            CheckPermission();
            CheckTabPage();
            gridOrderMenu.DataSource = sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);
        }
        #endregion

        #region [Check Navbarcontrol]
        private void CheckNavbarcontrol(string tabname)
        {
            for (int i = 0; i < navBarControl_menu.Groups.Count; i++)
            {
                navBarControl_menu.Groups[i].Visible = false;
            }
            switch (tabname)
            {
                case "Job Management":
                    navBarControl_menu.Groups["navBarGroup_JobList"].Visible = true;
                    break;
                case "Human Resource":
                    navBarControl_menu.Groups["navBarGroup_HR"].Visible = true;
                    break;
                case "Order Management":                    
                    navBarControl_menu.Groups["navBarGroup_CostingDetails"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_General"].Visible = true;                   
                    break;
                case "Matarial Management":
                    navBarControl_menu.Groups["navBarGroup_Source"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_MAList"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Booking"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Blaning"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Exception"].Visible = true;
                    break;
                case "WareHouse Management":
                    navBarControl_menu.Groups["navBarGroup_ImportMA"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ImportProduct"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ExportMA"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ExportProduct"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_StockAndException"].Visible = true;
                    break;
                case "Production Management":
                    navBarControl_menu.Groups["navBarGroup_Purchasing"].Visible = true; 
                    navBarControl_menu.Groups["navBarGroup_ProductionPlanning"].Visible = true;                    
                    navBarControl_menu.Groups["navBarGroup_FollowUp"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_DeleveryPlaning"].Visible = true;                       
                    break;
                case "Shipping Management":
                    navBarControl_menu.Groups["navBarGroup_ShippingAdvice"].Visible = true;   
                    break;
                case "Business Management":
                    break;
            }
        }      
        #endregion

        #region [Order Menu]
        private void gridViewmenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;

                //if (view.IsGroupRow(view.FocusedRowHandle) == true)
                //{
                //    if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                //    {
                //        month = null;                    
                //        cid = null;
                //    }
                //    else if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                //    {
                //        month = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                //        cid = null;
                //    }
                //}
                //else
                //{
                //    month = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                //    cid = view.GetFocusedDataRow()["Customer"].ToString();
                //}

                //if (frGV != null && frGV.IsDisposed == false)
                //{
                //    frGV.Select();
                //    frGV.LoadGV(Convert.ToInt32(view.GetFocusedDataRow()["Year"]), month,cid);
                //}
                //else
                //{
                //    frGV = new TabGeneralView(this);
                //    frGV.MdiParent = this;
                //    frGV.Show();
                //    frGV.LoadGV(Convert.ToInt32(view.GetFocusedDataRow()["Year"]), month, cid);
                //    //----------------------------
                //    Savelayout(frGV.Text, ribbon.SelectedPage.Text);
                //}

                if (view.IsGroupRow(view.FocusedRowHandle) == false && view.FocusedRowHandle>=0)
                {
                    int MPOID = Convert.ToInt32(view.GetFocusedDataRow()["MPOID"]);
                    frOrderDetails = new TabOrderDetails(MPOID);
                    frOrderDetails.MdiParent = this;
                    frOrderDetails.Show();
                    frOrderDetails.LoadData();
                    //----------------------------
                    Savelayout(frOrderDetails.Text, ribbon.SelectedPage.Text,strOrder);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;            
                }               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Event Ribbon FtyPurChase]
        private void FtyPurChase_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New Factory Purchase":
                    frFPM = new FrmFactoryPurchaseMaster(-1) { MdiParent = this, Text = "PO: Add new Factory Purchase" };                   
                    frFPM.LoadFPM();                    
                    frFPM.Show();
                    frFPM.NewFPM();
                    Savelayout(frFPM.Text, ribbon.SelectedPage.Text,strPurchasing);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed; 
                    break;
                case "Save":
                    if (frFPM != null && !frFPM.IsDisposed)
                    {
                        frFPM = ActiveMdiChild as FrmFactoryPurchaseMaster;
                        frFPM.UpdateFPM();
                        frFPM.LoadFPM();
                        Savelayout(frFPM.Text, ribbon.SelectedPage.Text, strPurchasing);
                    }                    
                    break;
                case "Delete":
                    if (frFPM != null && !frFPM.IsDisposed)
                    {
                        frFPM.DeleteFtyPurMaster();
                        this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
                    }                           
                    break;
                case "Refresh":
                    if (frFPM != null && !frFPM.IsDisposed)
                    {
                        this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
                        frFPM.LoadFPM();
                    }
                    break;
                default:
                    FrmApprovingManagement frmAM = new FrmApprovingManagement();                    
                    frmAM.MdiParent = this;
                    frmAM.Show();
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed; 
                    break;
            }
        }
        #endregion

        #region[Purchasing Menu]
        private void gridView_Purchasing_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int fpid = Convert.ToInt32(gridView_Purchasing.GetFocusedDataRow()[0]);
                string title ="PO: "+ gridView_Purchasing.GetFocusedDataRow()["PONo"].ToString();
                ClassShare.fpid = fpid;               
                int flag=0;
                foreach(string item in Pages)
                {                   
                    if (frFPM != null && frFPM.IsDisposed == false && title == item)
                    {
                        frFPM.Select();
                        flag=1;
                        break;
                    }
                }
                if (flag == 0)
                {                    
                    frFPM = new FrmFactoryPurchaseMaster(fpid);
                    frFPM.MdiParent = this;
                    frFPM.Text = title;
                    frFPM.LoadFPM();
                    frFPM.Show();
                    Pages.Add(title);
                    Savelayout(frFPM.Text, ribbon.SelectedPage.Text,strPurchasing);
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;         
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }        
        }
        #endregion

        //Material Management

        #region [Material Menu]
        private void gridView_MAList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int malid = Convert.ToInt16(gridView_MAList.GetFocusedDataRow()["MALID"]);                
                frSD = new FrmStyleDetails(malid);
                frSD.MdiParent = this;
                frSD.LoadData();
                frSD.Text = "MAPO: " + gridView_MAList.GetFocusedDataRow()["MALNo"].ToString();               
                frSD.Show();
                frSD.RunBackroundWorker();
                Savelayout(frSD.Text,"Matarial Management",strMAList);
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Refresh Material]
        private void RefreshMaterial()
        {
            sp_MAListMasterLoadTableAdapter.Fill(dataSetMatarial.sp_MAListMasterLoad);
        }
        #endregion

        #region [Event Ribbon Material]
        private void Matarial_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "New Material List":
                        frSD = new FrmStyleDetails(-1) { MdiParent = this, Text = "Add new Matarial" };                      
                        frSD.Show();
                        frSD.AddNew();
                        frSD.LoadData();
                        Savelayout(frSD.Text, ribbon.SelectedPage.Text,strMAList);
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Save":
                        try
                        {
                            if (frSD != null && !frSD.IsDisposed)
                            {
                                frSD.UpdateData();
                                frSD.LoadData();
                                this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
                                Savelayout(frSD.Text, ribbon.SelectedPage.Text, strMAList);
                            }
                        }
                        catch (Exception ex)
                        {
                             MessageBox.Show(ex.Message + "\n Nothing to update !!!");
                        }
                        break;
                      
                    case "Delete":
                        if (frSD != null && !frSD.IsDisposed)
                        {
                            frSD.DeleteMaster();
                            RefreshMaterial();
                            this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
                            frSD.RunBackroundWorker();
                        }
                        break;
                    case "Refresh":
                        sp_MAListMasterLoadTableAdapter.Fill(dataSetMatarial.sp_MAListMasterLoad);
                        sp_BAMenuTableAdapter.Fill(dataSetBalancing.sp_BAMenu);
                        if (frSD != null && !frSD.IsDisposed)
                        {
                            RefreshMaterial();
                            frSD.RunBackroundWorker();
                        }
                        break;
                    case "Preview":
                        if (frSD != null && !frSD.IsDisposed)                        
                            frSD.Preview();                       
                        break;
                    case "Confirm Cons":
                        frCFC = new FrmConfirmCons();
                        frCFC.LoadData("Waiting");
                        frCFC.Show();
                        break;
                    case "Import Costing":
                        if (frSD != null && !frSD.IsDisposed)
                            frSD.ImportCosting();                         
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Change Item Menu]

        //*********************************************************************************
        private void navBarControl_menu_Change(object sender, EventArgs e)
        {
            SelectedPageGroup(navBarControl_menu.ActiveGroup.Caption);
        }      

        //*************************************************************************************
        
        #endregion
        
        #region[MALibrary]

        private void bnt_Fabric_Click(object sender, EventArgs e)
        {
            if (frMAGV != null && frMAGV.IsDisposed == false)
            {
                frMAGV.Select();
                frMAGV.LoadMAGV(DateTime.Now.Year," Fabric");                
            }
            else
            {
                frMAGV = new FrmMAGeneralView(this);
                frMAGV.MdiParent = this;
                frMAGV.Show();
                frMAGV.LoadMAGV(DateTime.Now.Year, " Fabric");
                ClassShare.frFabricGV = frMAGV;
                //----------------------------
                Savelayout(frMAGV.Text, ribbon.SelectedPage.Text,strMASource);
            }
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }

        private void bnt_Material_Click(object sender, EventArgs e)
        {
            if (frAV != null && frAV.IsDisposed == false)
            {
                frAV.Select();
                frAV.LoadMAGV(DateTime.Now.Year, "Accessories");
            }
            else
            {
                frAV = new FrmAccessoriesView(this);
                frAV.MdiParent = this;
                frAV.Show();
                frAV.LoadMAGV(DateTime.Now.Year, "Accessories");
                ClassShare.frAcessV = frAV;
                //----------------------------
                Savelayout(frAV.Text, ribbon.SelectedPage.Text, strMASource);
            }
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }
        #endregion

        //Material Library
        #region [Update Material Libary]
        private void MALibrary_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "Fabric":
                        frMALib = new FrmMALibrary(-1);
                        //frMALib.MdiParent = this;
                        frMALib.Text = "Add new Fabric Library";                        
                        frMALib.Show();
                        frMALib.AddNew();
                        frMALib.LoadData();                        
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Accessories":
                        frMA = new FrmMaterial(-1);
                       // frMA.MdiParent = this;
                        frMA.Text = "Add new Accessories Library";
                        frMA.Show();
                        frMA.AddNew();
                        frMA.LoadData();                      
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;           
                    case "Refresh":                     
                        if (frMAGV != null && frMAGV.IsDisposed == false)
                        {
                            frMAGV.LoadMAGV(DateTime.Now.Year," Fabric");
                        }
                        if (frAV != null && frAV.IsDisposed == false)
                        {
                            frAV.LoadMAGV(DateTime.Now.Year, "Accessories");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion       

        #region [RefreshMALibaryMenu]
        public void RefreshMALibaryMenu()
        {
            sp_MALibraryMenuTableAdapter.Fill(dataSetMatarial.sp_MALibraryMenu);
        }
        #endregion
        //-------------------
        //Job Management

        #region[Refresh JobMenu]
        public void RefreshJobMenu()
        {
            this.sp_JobMenuTableAdapter.Fill(this.dataSet_JobManagement.sp_JobMenu, ClassShare.Usid,"All");
        }
        #endregion

        #region [Event Menu]
        private void gridView_JobManage_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (!view.IsGroupRow(view.FocusedRowHandle))
                {
                    JID = Convert.ToInt32(view.GetFocusedDataRow()["JID"]);
                    frJobM = new FrmJobManagement(JID, true);
                    frJobM.Show();
                    frJobM.LoadData();
                    Savelayout(frJobM.Text, ribbon.SelectedPage.Text,strJobList);       
                }             
            }
            catch
            {
                MessageBox.Show("Disconnect Database! Try connect to again!", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Event Ribbon Job]
        private void JobItem_Click(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {                    
                    case "New Job":
                        frJobM = new FrmJobManagement(-1,true) { MdiParent = this, Text = "Add new Job" };
                        frJobM.Show();
                        frJobM.AddNew();
                        frJobM.LoadData();
                        frJobM.CheckButton();
                        Savelayout(frJobM.Text, ribbon.SelectedPage.Text,strJobList);
                        break;
                    case "Create From Job":
                        frJobM = new FrmJobManagement(-1, false) { MdiParent = this, Text = "Add new Job" };
                        frJobM.Show();
                        frJobM.AddNew();
                        frJobM.LoadData();
                        frJobM.CheckButton();
                        Savelayout(frJobM.Text, ribbon.SelectedPage.Text, strJobList);
                        break;
                    case "<<Assign>>":
                        if (frJobM != null && !frJobM.IsDisposed)
                        {
                            frJobM.UpdateJob();                            
                            sp_JobMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobMenu, ClassShare.Usid,"All");
                            if (frJobView != null || !frJobView.IsDisposed)
                                frJobView.LoadData();  
                            
                        }
                        RefreshJobMenu();
                        //frJobM.LoadData();
                        break;
                    case "Delete":
                        break;
                    case "Assign/Receive":
                        sp_JobMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobMenu, ClassShare.Usid,"All");
                        if (frJobView != null || !frJobView.IsDisposed)
                            frJobView.LoadData();
                        break;
                    case "All Job":
                        if (frJobGr != null && !frJobGr.IsDisposed)
                            frJobGr.Select();
                        else
                        {
                            frJobGr = new FrmJobGeneral(this) { MdiParent = this };
                            frJobGr.Show();
                            frJobGr.LoadData();
                            Savelayout(frJobGr.Text, ribbon.SelectedPage.Text, strJobList);
                        }
                        // navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Print":
                        FrmSetupReport frmJobReport = new FrmSetupReport();                        
                        frmJobReport.ShowDialog();
                        break;
                    case "Statistical":
                        if (frJobStatistic != null && !frJobStatistic.IsDisposed)
                            frJobStatistic.Select();
                        else
                        {
                            frJobStatistic = new FrmJobStatistic() { MdiParent=this};
                            frJobStatistic.Show();
                        }
                        break;   
                    case "Job Ganeral View":
                        if (frJobView != null && !frJobView.IsDisposed)
                            frJobView.Select();
                        else
                        {
                            frJobView = new FrmJobView();
                            frJobView.Show();
                            frJobView.MdiParent = this;
                            frJobView.LoadData();
                            Savelayout(frJobView.Text, ribbon.SelectedPage.Text, strJobList);
                        }
                        break;
                }
            }
            catch
            {
               
            }
        }
        #endregion  

        #region [Alarms New Job]
        private void timer_job_Tick(object sender, EventArgs e)
        {
            try
            {                
                Timejob++;
                if (Timejob == 90)
                {
                    DataTable dtb = cls.GetData("sp_JobAlertNewJob", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            //AlertInfo info = new AlertInfo("New Job", " You have a new job '" + dtb.Rows[i]["Title"] + "'", imageCollection_Alert.Images[0]);
                            //alertControl_info.Show(this, info);
                            //JID = Convert.ToInt32(dtb.Rows[i]["JID"]);
                            if (NewJobID != Convert.ToInt32(dtb.Rows[i]["JID"]))
                            {
                                NewJobID = Convert.ToInt32(dtb.Rows[i]["JID"]);
                                frJobM = new FrmJobManagement(NewJobID, true);
                                Size s = new Size();
                                s = SystemInformation.WorkingArea.Size;
                                frJobM.WindowState = FormWindowState.Maximized;
                                frJobM.Size = s;
                                frJobM.TopMost = true;
                                frJobM.FormBorderStyle = FormBorderStyle.None;
                                frJobM.LoadData();
                                frJobM.ShowDialog(); 
                            }
                        }
                    if (frJobView != null || !frJobView.IsDisposed)
                        frJobView.loadUscJobView("All");                  
                    Timejob = 0;
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Timer Job]
       
        private void timer_JobRequie_Tick(object sender, EventArgs e)
        {
            TimeAlert++;
            if (TimeAlert == 240)
            {
                try
                {
                    sp_JobAlertTableAdapter.Fill(dataSet_JobManagement.sp_JobAlert, ClassShare.Usid);
                    DataTable dtbJobAlert = sp_JobAlertTableAdapter.GetData(ClassShare.Usid);
                    for (int i = 0; i < dtbJobAlert.Rows.Count; i++)
                        {
                            if (Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) <= 300 && Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) > 0)
                            {
                                JID = Convert.ToInt32(dtbJobAlert.Rows[i]["JID"]);
                                AlertInfo info = new AlertInfo("Job expired", "Your job '" + dtbJobAlert.Rows[i]["Title"].ToString() + "'\n Just " + dtbJobAlert.Rows[i]["Hour"].ToString() + "  munite is expired",imageCollection_Alert.Images[1]);
                                alertControl_info.Show(this, info);
                            }
                            else
                            {                              
                                if (Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) <= 0)
                                {
                                    AlertInfo info = new AlertInfo("Job Fail", "Your job '" + dtbJobAlert.Rows[i]["Title"].ToString() + "'\n was Failed!", imageCollection_Alert.Images[2]);
                                    alertControl_info.Show(this, info);
                                    JID = Convert.ToInt32(dtbJobAlert.Rows[i]["JID"]);
                                    cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { Convert.ToInt64(dtbJobAlert.Rows[i]["JID"]), ClassShare.Usid, "Failed", "Not Comment", 2 });
                                    //cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { JID, DateTime.Now, " Failed", 1 });
                                }                                
                            }
                        }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeAlert = 0;
            }
        }

        private void timer_JobRequester_Tick(object sender, EventArgs e)
        {
            TimeRequester++;
            if (TimeRequester == 180)
            {
                try
                {
                    DataTable dtbRequester = cls.GetData("sp_JobRequester", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int index = 0; index < dtbRequester.Rows.Count; index++)
                    {
                        if (Convert.ToInt16(dtbRequester.Rows[index]["Hour"]) < 2 && Convert.ToInt16(dtbRequester.Rows[index]["Hour"]) > 0)
                        {
                            AlertInfo info = new AlertInfo("Job Approval", "Your job require '" + dtbRequester.Rows[index]["Title"].ToString() + "'\n Just 1 hour is approval", imageCollection_Alert.Images[3]);
                            alertControl_info.Show(this, info);
                            JID = Convert.ToInt32(dtbRequester.Rows[index]["JID"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeRequester = 0;
            }
        }

        private void timer_NotAccept_Tick(object sender, EventArgs e)
        {
            TimeNotAccept++;
            if (TimeNotAccept == 300)
            {
                try
                {
                    DataTable dtb_notaccept = cls.GetData("sp_JobAlerNotAccept", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int i = 0; i < dtb_notaccept.Rows.Count; i++)
                    {
                        AlertInfo info = new AlertInfo("Job not accept", dtb_notaccept.Rows[i]["FullName"].ToString() + " doesn't accept the job '" + dtb_notaccept.Rows[i]["Title"].ToString() + "'\n that you assign!",imageCollection_Alert.Images[4]);
                        alertControl_info.Show(this, info);
                        //MailMessage message = new MailMessage();
                        //SmtpClient Client = new SmtpClient();
                        //Client.Host = "smtp.gmail.com";
                        //Client.Port = 587;
                        //Client.Credentials = new System.Net.NetworkCredential("comosoft.como@gmail.com", "@Comosoft324");
                        //Client.EnableSsl = true;
                        //Client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        //message.From = new MailAddress(ClassShare.Email);
                        //message.Sender = new MailAddress(ClassShare.Email);

                        //message.To.Add(new MailAddress(ClassShare.Email));
                        //message.To.Add(new MailAddress(dtb_notaccept.Rows[i]["Email"].ToString()));

                        //message.Subject = " COMOSOFT - Not Accept Job";
                        //message.Body = "COMOSOFT Notify: " + dtb_notaccept.Rows[i]["FullName"].ToString() + " not yet accept the job '" + dtb_notaccept.Rows[i]["Title"].ToString();
                        //message.IsBodyHtml = true;
                        //Client.Send(message);
                        JID = Convert.ToInt32(dtb_notaccept.Rows[i]["JID"]);
                    }                   
                    TimeNotAccept = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void timer_AlertSubmit_Tick(object sender, EventArgs e)
        {
            TimeSubmit++;
            if (TimeSubmit == 120)
            {
                try
                {
                    //Alert Job Submit
                    DataTable dtbSubmit,dtConfirmCons;
                    int index;
                    dtbSubmit = cls.GetData("sp_JobAlertSubmit", new string[] { "@EID" }, new object[] { ClassShare.Usid });                    
                    for (index = 0; index < dtbSubmit.Rows.Count; index++)
                    {
                        AlertInfo info = new AlertInfo("Submiting....", dtbSubmit.Rows[index]["FullName"].ToString()+" Submit the job '"+ dtbSubmit.Rows[index]["Title"].ToString() + "' for you", imageCollection_Alert.Images[5]);
                        alertControl_info.Show(this, info);
                        JID = Convert.ToInt32(dtbSubmit.Rows[index]["JID"]);
                    }
                    //Alert ConfirmCons
                    dtConfirmCons = cls.GetData("sp_MAConfirmCons", new string[] { "@EID", "@Status" }, new object[] { ClassShare.Usid, "Waiting" });
                    for (index = 0; index < dtConfirmCons.Rows.Count; index++)
                    {
                        AlertInfo info = new AlertInfo("Submiting....", dtConfirmCons.Rows[index]["FullName"].ToString()+" submit for you confirm Cons...", imageCollection_Alert.Images[7]);
                        alertControl_MA.Show(this, info);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeSubmit = 0;
            }
        }

        private void timer_JobRequestTime_Tick(object sender, EventArgs e)
        {
            RequestTime++;
            if (RequestTime == 90)
            {
                DataTable dtb = cls.GetData("sp_JobAlertRequestTime", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    AlertInfo info = new AlertInfo("Comfirm Request Time", dtb.Rows[i]["FullName"].ToString() + " require more time!", imageCollection_Alert.Images[1]);
                    alertControl_info.Show(this, info);
                    JID = Convert.ToInt32(dtb.Rows[i]["JID"]);
                }
                RequestTime = 0;
            }
        }

        private void timer_JobExpire_Tick(object sender, EventArgs e)
        {
            TimeJobEx++;
            if (TimeJobEx == 10)
            {
                try
                {
                    DataTable dtJobEx = cls.GetData("sp_JobSubmiterExpire");
                    for (int i = 0; i < dtJobEx.Rows.Count; i++)
                    {
                        //cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { dtJobEx.Rows[i]["JID"], DateTime.Now, "  Failed", 1 });
                        cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { dtJobEx.Rows[i]["JID"], dtJobEx.Rows[i]["EID"], "Failed", "", 2 });
                    }
                    RefreshJobMenu();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeJobEx = 0;
            }
        }

        #endregion

        #region [Click Alert]
        private void alertControl_info_AlertClick(object sender, AlertClickEventArgs e)
        {
            try
            {
                frJobM = new FrmJobManagement(JID, true);
                frJobM.Show();
                frJobM.LoadData();
                Savelayout(frJobM.Text, ribbon.SelectedPage.Text, strJobList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void alertControl_MA_AlertClick(object sender, AlertClickEventArgs e)
        {
            try
            {
                if (frCFC != null && !frCFC.IsDisposed)
                {
                    frCFC.Select();
                }
                else
                {
                    frCFC = new FrmConfirmCons();

                    frCFC.Show();
                }
                frCFC.LoadData("Waiting");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        //-------------------

        //System
        #region [User Info]
        private void System_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "Logout":
                        if (File.Exists(ClassShare.lcSystem + @"\config.dat"))
                            File.Delete(ClassShare.lcSystem + @"\config.dat");
                        ClassShare.IsRemember = false;
                        this.Hide();
                        FrmLogin frmlogin = new FrmLogin();
                        frmlogin.ShowDialog();                        
                        break;
                    case "Change Password":
                        FrmChangePassword frmchangepass = new FrmChangePassword();
                        frmchangepass.ShowDialog();
                        break;
                    case "Exit":
                        this.Close();                        
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [SaveLayout]
        public void Savelayout(string formname, string pagename, string NavBarName)
        {
            _Layout Node = new _Layout();
            Node.formname = formname;
            Node.pagename = pagename;
            Node.NavBarName = NavBarName;
            ListLayout.Add(Node);
        }
        #endregion

        #region [Selecte Tabpage]
        private void xtraTabbedMdiManager_TabForm_SelectedPageChanged(object sender, EventArgs e)
        {
            try
            {
                string name = xtraTabbedMdiManager_TabForm.SelectedPage.Text;
                foreach (_Layout item in ListLayout)
                {
                    if (name == item.formname)
                    {
                        ribbon.SelectedPage =Ribbon.Pages[item.pagename];
                        SelectPage(item.pagename);                    
                        SelectedPageGroup(item.NavBarName);
                    }
                }
            }
            catch
            {                
            }
        }
        #endregion

        #region[AutoUpdate]

        private void CheckUpdate()
        {
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                ad = ApplicationDeployment.CurrentDeployment;
                try
                {
                    info = ad.CheckForDetailedUpdate();
                }
                catch (DeploymentDownloadException dde)
                {
                    MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
                    return;
                }
                catch (InvalidDeploymentException ide)
                {
                    MessageBox.Show("Cannot check for a new version of the application. Please redeploy the application and try again. Error: " + ide.Message);
                    return;
                }
                catch (InvalidOperationException ioe)
                {
                    MessageBox.Show("This application cannot be updated. Error: " + ioe.Message);
                    return;
                }

                if (info.UpdateAvailable)
                {
                    Boolean doUpdate = true;

                    if (!info.IsUpdateRequired)
                    {
                        //DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
                        //if (!(DialogResult.OK == dr))
                        //{
                        doUpdate = true;
                        // }
                    }
                    else
                    {
                        // Display a message that the app MUST reboot. Display the minimum required version.
                        MessageBox.Show("This application has detected a mandatory update from your current " +
                            "version to version " + info.MinimumRequiredVersion.ToString() +
                            ". The application will now install the update and restart.",
                            "Update Available", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    }
                    if (doUpdate)
                    {
                        try
                        {
                            ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);
                            ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
                            ad.UpdateAsync();
                        }
                        catch (DeploymentDownloadException dde)
                        {
                            MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
                            return;
                        }
                    }
                }
            }
        }
        private void bnt_JobCheckUpdate_ItemClick(object sender, ItemClickEventArgs e)
        {
            CheckUpdate();
        }
        void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage >= 0)
            {
                dockPanel_Update.Show();
            }
            progressBar.EditValue = e.ProgressPercentage;
            lab_Updating.Text = "Updating new version..." + e.ProgressPercentage.ToString() + " %";
        }
        void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                MessageBox.Show("Cancelled");
            }
            else if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            dockPanel_Update.Hide();
            Application.Restart();
        }
        #endregion

        #region[Click Notifi Update]
        private void timer_CheckUpdate_Tick(object sender, EventArgs e)
        {
            TimeCheckUpdate++;
            if (TimeCheckUpdate == 3600)
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ad = ApplicationDeployment.CurrentDeployment;

                    try
                    {
                        info = ad.CheckForDetailedUpdate();
                    }
                    catch
                    {
                    }

                    if (info.UpdateAvailable)
                    {
                        notifyIcon_comosoft.ShowBalloonTip(3000, "Comosoft Update Available", "A new version of Comosoft is ready to be installed! \n Click here to continue.", ToolTipIcon.Info);
                    }
                }
                TimeCheckUpdate = 0;
            }
        }

        private void notifyIcon_comosoft_BalloonTipClicked(object sender, EventArgs e)
        {
            try
            {
                ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);
                ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
                ad.UpdateAsync();
            }
            catch (DeploymentDownloadException dde)
            {
                MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
                return;
            }
        }
        #endregion

        #region [NotifiMenu]
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (File.Exists(ClassShare.lcSystem + @"\config.dat"))
                File.Delete(ClassShare.lcSystem + @"\config.dat");
            ClassShare.IsRemember = false;
            this.Hide();
            FrmLogin frmlogin = new FrmLogin();
            frmlogin.ShowDialog();
        }

        private void checkUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckUpdate();
        }
        #endregion

        //Book an Balance
        #region [BA Menu]
        private void bnt_OK_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_Balancing as GridView;
                Items = null;
                int[] rows = view.GetSelectedRows();
                foreach (int i in rows)
                {
                    if (!view.IsGroupRow(i))
                    {
                        Items += view.GetDataRow(i)["MALID"].ToString() + ',';
                    }
                }
                Items = Items.Substring(0, Items.Length - 1);
          
                frBaGV = new FrmBAGaneralView(Items) { MdiParent = this };
                frBaGV.LoadData();
                frBaGV.Show();
                view.ClearSelection();
                Savelayout("Balancing View", "Matarial Management",strBlance);
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void Balancing_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "Save":
                    if (frBaGV != null && !frBaGV.IsDisposed)
                        frBaGV.SaveBA();
                    sp_BalanceMenuTableAdapter.Fill(dataSetBalancing.sp_BalanceMenu);
                    break;
                case "Refresh":
                    if (frBaGV != null && !frBaGV.IsDisposed)
                        frBaGV.LoadData();
                    break;
                case "Preview":
                    if (frBaGV != null && !frBaGV.IsDisposed)
                        frBaGV.BAPreview();
                    break;
            }
        }

        private void gridView_BalanceList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (!view.IsGroupRow(view.FocusedRowHandle) && view.FocusedRowHandle >= 0)
                {
                    Items = null;
                    Items = view.GetFocusedDataRow()["MALIDs"].ToString();
                    frBaGV = new FrmBAGaneralView(Items) { MdiParent = this };
                    frBaGV.LoadData();
                    frBaGV.Text = view.GetFocusedDataRow()["Name"].ToString();
                    frBaGV.Show();
                    Savelayout("Balancing View", "Matarial Management", strBlance);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        
        #region[Book Menu]
        private void gridView_BookMenu_DoubleClick(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsGroupRow(view.FocusedRowHandle))
            {
                int ID = Convert.ToInt32(view.GetDataRow(view.FocusedRowHandle)["BMID"]);
                frBMA = new FrmBookMA(ID) { MdiParent = this };
                frBMA.loadData();
                frBMA.Show();
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
        }
        private void BookMA_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New Book MA":
                    frBMA = new FrmBookMA(-1) { MdiParent = this, Text = "Add New Book Material" };
                    frBMA.Show();
                    frBMA.AddNew();
                    frBMA.loadData();
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    break;
                case "Save":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        frBMA.UpdateData();
                        frBMA.loadData();
                    }
                    break;
                case "Delete":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        frBMA.UpdateData();
                    }
                    sp_BookMAMenuTableAdapter.Fill(dataSetBalancing.sp_BookMAMenu);
                    break;
                case "Refresh":
                    sp_BookMAMenuTableAdapter.Fill(dataSetBalancing.sp_BookMAMenu);
                    if (frBMA != null && !frBMA.IsDisposed)
                    {                        
                        frBMA.loadData();
                    }
                    break;
                case "Preview":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        frBMA.Preview();                        
                    }                    
                    break;
               default:
                    break;
            }
        }
        #endregion

        //WareHouse
        #region [MA Import]
        private void ImportMA_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New Import Material":
                    frImportMA=new FrmImportMA(-1){Text="New Import Material", MdiParent=this};                   
                    frImportMA.LoadData();
                    frImportMA.Show();
                    frImportMA.AddNew();
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    Savelayout(frImportMA.Text, ribbon.SelectedPage.Text,strIptMA);
                    break;
                case "Save":
                    if (frImportMA != null && !frImportMA.IsDisposed)
                    {
                        frImportMA.UpdateData("Update");
                        Savelayout(frImportMA.Text, ribbon.SelectedPage.Text, strIptMA);
                    }
                    break;
                case "Delete":
                    if (frImportMA != null && !frImportMA.IsDisposed)
                    {
                        frImportMA.UpdateData("Delete");                       
                    }
                    sp_MAIPMenuTableAdapter.Fill(dataSet_WareHouse.sp_MAIPMenu);
                    break;
                case "Refresh":
                    sp_MAIPMenuTableAdapter.Fill(dataSet_WareHouse.sp_MAIPMenu);
                    if (frImportMA != null && !frImportMA.IsDisposed)
                    {
                        frImportMA.LoadData();                        
                    }
                    break;
                case "Print":
                    if (frImportMA != null && !frImportMA.IsDisposed)
                    {
                        frImportMA.Preview();                      
                    }                    
                    break;
            }
        }
        //Import Material
        private void gridView_ImportMAMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                {
                    iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                    obMonth = null;
                    obSuplier = null;
                    bGV = true;
                }
                else
                {
                    if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                    {
                        iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                        obMonth = view.GetFocusedDataRow()["Month"];
                        obSuplier = null;
                        bGV = true;
                    }
                    else
                    {
                        if (view.GetRowLevel(view.FocusedRowHandle) == 2)
                        {
                            iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                            obMonth = view.GetFocusedDataRow()["Month"];
                            obSuplier = view.GetFocusedDataRow()["MASUPID"];
                            bGV = true;
                        }
                        else
                        {
                            int MAIID = Convert.ToInt32(view.GetFocusedDataRow()["MAIID"]);
                            frImportMA = new FrmImportMA(MAIID);
                            frImportMA.LoadData();
                            frImportMA.MdiParent = this;
                            frImportMA.Text = "Import No: " + view.GetFocusedDataRow()["MAINo"].ToString();
                            frImportMA.Show();
                            Savelayout(frImportMA.Text, ribbon.SelectedPage.Text, strIptMA);
                        }
                    }
                }
                if (bGV == true)
                {
                    frIptMAGV = new FrmImportMAGaneral(iYear, obMonth, obSuplier) { MdiParent = this, Text = "Import Ganeral View" };
                    frIptMAGV.LoadData();
                    frIptMAGV.Show();
                    bGV = false;
                    Savelayout(frIptMAGV.Text, ribbon.SelectedPage.Text, strIptMA);
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }       
        #endregion
       
        #region[MA Export]
        private void ExportMA_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption.ToString())
            {
                case "New Export Material":
                    frExMA = new FrmExportMA(-1){ MdiParent=this, Text="Add New Export Material"};
                    frExMA.Show();
                    frExMA.LoadData();
                    frExMA.AddNew();
                    Savelayout(frExMA.Text, ribbon.SelectedPage.Text,strEptMA);
                    break;
                case "Save":
                    if (frExMA != null && !frExMA.IsDisposed)
                    {
                        frExMA.UpdateData("Update");
                        Savelayout(frExMA.Text, ribbon.SelectedPage.Text, strEptMA);
                    }                    
                    break;
                case "Delete":
                    if (frExMA != null && !frExMA.IsDisposed)
                    {
                        frExMA.UpdateData("Delete");
                    }
                    sp_WHExportMenuTableAdapter.Fill(dataSet_WareHouse.sp_WHExportMenu);
                    break;
                case "Refresh":
                    sp_WHExportMenuTableAdapter.Fill(dataSet_WareHouse.sp_WHExportMenu);
                    if (frExMA != null && !frExMA.IsDisposed)
                    {
                        frExMA.LoadData();
                    }
                    break;
                case "Preview":
                     if (frExMA != null && !frExMA.IsDisposed)
                     {
                         frExMA.Preview();
                     }                    
                    break;
            }
        }

        private void gridView_MAExportMenu_DoubleClick(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsGroupRow(view.FocusedRowHandle) && view.FocusedRowHandle >= 0)
            {
                int MAEID = Convert.ToInt32(view.GetFocusedDataRow()["MAEID"]);
                frExMA = new FrmExportMA(MAEID) { MdiParent = this, Text = "Export No: " + view.GetFocusedDataRow()["MAENo"].ToString() };                
                frExMA.LoadData();                
                frExMA.Show();
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                Savelayout(frExMA.Text, ribbon.SelectedPage.Text, strEptMA);
            }
        }
     #endregion

        #region[Stock And Exception]
        private void Stock_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "Stock Ganeral":
                    if (frSGV != null && !frSGV.IsDisposed)
                    {
                        frSGV.Select();
                        frSGV.LoadData();
                    }
                    else
                    {
                        frSGV = new FrmStockGaneralView();
                        frSGV.MdiParent = this;
                        frSGV.LoadData();
                        frSGV.Show();
                        Savelayout(frSGV.Text, ribbon.SelectedPage.Text,strStock);
                    }
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    break;
                case "Add Stock":
                    if (frSGV != null && !frSGV.IsDisposed)
                    {
                        frSGV.ShowPanel();                       
                    }                    
                    break;
                case "Clear Stock":
                    if (frSGV != null && !frSGV.IsDisposed)
                    {
                        frSGV.ClareStock();
                    } 
                    break;
            }
        }
        #endregion

        #region[HR]
        private void bnt_EmployeeList_Click(object sender, EventArgs e)
        {
            if (frEList != null && !frEList.IsDisposed)
            {
                frEList.Select();
            }
            else
            {
                frEList=new FrmEmployeeList(){MdiParent=this};
                frEList.Show();
                frEList.LoadData();               
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;   
            }
        }
        private void bnt_HRRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "Refresh":
                    if (frEList != null && !frEList.IsDisposed)
                    {
                        frEList.RefreshData();
                    }
                    break;
                case "Preview":
                    if (frEList != null && !frEList.IsDisposed)
                    {
                        frEList.PreView();
                    }
                    break;
            }       
        }
        #endregion

        #region[Product Import]
        private void ProdcutImport_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New Product Import":
                    frImptProduct = new FrmImportProduct(-1) { MdiParent = this, Text = "New Import Product" };
                    frImptProduct.LoadData();                                      
                    frImptProduct.Show();
                    frImptProduct.AddNew();  
                    Savelayout(frImptProduct.Text, ribbon.SelectedPage.Text,strIptPro);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    break;
                case "Save":
                    if (frImptProduct != null && !frImptProduct.IsDisposed)
                    {
                        frImptProduct.UpdateProductImport("Update");
                        Savelayout(frImptProduct.Text, ribbon.SelectedPage.Text, strIptPro);
                    }
                    break;
                case "Delete":
                    if (frImptProduct != null && !frImptProduct.IsDisposed)
                    {
                        frImptProduct.UpdateProductImport("Delete");
                    }
                    break;
                default:
                    if (frImptProduct != null && !frImptProduct.IsDisposed)
                    {
                        frImptProduct.LoadData();
                    }
                    break;
            }            
        }

        private void gridView_ImportProductMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view.FocusedRowHandle >= 0 && !view.IsGroupRow(view.FocusedRowHandle))
                {
                    int intPrIID = Convert.ToInt32(view.GetFocusedDataRow()["PRIID"]);
                    frImptProduct = new FrmImportProduct(intPrIID) { MdiParent = this };
                    frImptProduct.LoadData();
                    frImptProduct.Show();
                    Savelayout(frImptProduct.Text, ribbon.SelectedPage.Text, strIptPro);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
        #endregion

        //Production
        #region[Production]
        private void Production_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption.ToString())
            {
                case "New Plan":
                    //frProPlan = new FrmProductionPlanning() { MdiParent=this,Text="Add new production planning"};                   
                    //frProPlan.LoadData();
                    //frProPlan.Show();
                    //Savelayout(frProPlan.Text, ribbon.SelectedPage.Text);
                    break;
                case "Save":
                    break;
                case "Delete":
                    break;
                case "Refresh":
                    sp_ProductionPlanMenuTableAdapter.Fill(dataSet_Production.sp_ProductionPlanMenu);
                    if (frOrderInfo != null && !frOrderInfo.IsDisposed)
                    {
                        frOrderInfo.LoadData();
                    }
                    if (frProPlan != null && !frProPlan.IsDisposed)
                    {
                        frProPlan.LoadData();
                    }
                    break;
                case "Preview":                    
                    break;
                case "Order List":
                    if (frOrderInfo != null && !frOrderInfo.IsDisposed)
                    {
                        frOrderInfo.Select();
                        frOrderInfo.LoadData();
                    }
                    else
                    {
                        frOrderInfo = new FrmOrderInfo() { MdiParent=this};
                        frOrderInfo.LoadData();
                        frOrderInfo.Show();

                    }
                    break;
            }
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }
        #endregion

        #region[Redo-Undo Form]
        private void bnt_Undo_ItemClick(object sender, ItemClickEventArgs e)
        {
            xtraTabbedMdiManager_TabForm.SetNextMdiChildMode = DevExpress.XtraTabbedMdi.SetNextMdiChildMode.Windows;
        }

        private void bnt_Redo_ItemClick(object sender, ItemClickEventArgs e)
        {
        }
        #endregion

        #region[FollowUp]
        private void FollowUp_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption.ToString())
            {               
                case "Refresh":
                    if (frPOP != null && !frPOP.IsDisposed)
                    {                       
                        frPOP.LoadData();
                    }
                    break;
                case "Preview":
                    if (frPOP != null && !frPOP.IsDisposed)
                    {
                        frPOP.Preview();
                    }
                    break;
            }
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }
        #endregion

        #region [Follow]
        private void gridView_FollowMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_FollowMenu as GridView;
                if (view.FocusedRowHandle >= 0)
                {
                    obYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                    obMonth = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                    obOID = Convert.ToInt32(view.GetFocusedDataRow()["OID"]);
                    obSubIID = Convert.ToInt32(view.GetFocusedDataRow()["SubIID"]);
                    obSubFLID = Convert.ToInt32(view.GetFocusedDataRow()["SubFLID"]);
                    frPOP = new FrmProductionOutlinePlanningDaily(obYear, obMonth, obOID, obSubIID, obSubFLID);
                    frPOP.LoadData();
                    frPOP.MdiParent = this;
                    frPOP.Show();
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }     
        #endregion

        #region [Production Plan Menu]

        private void gridView_ProductionPlanMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_ProductionPlanMenu as GridView;               
                if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                {
                    iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                    obMonth = null;
                }
                if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                {
                    iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                    obMonth = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                    obOID = null;
                    obSubIID = null;
                    obSubFLID = null;
                }
                else
                {
                    iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                    obMonth = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                    obOID = Convert.ToInt32(view.GetFocusedDataRow()["OID"]);
                    obSubIID = Convert.ToInt32(view.GetFocusedDataRow()["SubIID"]);
                    obSubFLID = Convert.ToInt32(view.GetFocusedDataRow()["SubFLID"]);
                }
                frProPlan = new FrmProductionPlanning(iYear, obMonth, obOID, obSubIID, obSubFLID) { MdiParent = this };
                frProPlan.LoadData();
                frProPlan.Show();
                Savelayout(frProPlan.Text, ribbon.SelectedPage.Text,strProPlanning);                
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Delivery Menu]
        private void gridView_DeliveryMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                flag = true;
                GridView view = gridView_DeliveryMenu as GridView;
                if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                {
                    obYear = view.GetFocusedDataRow()["Year"];
                    obMonth = null;
                }
                else
                {
                    if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                    {
                        obYear = view.GetFocusedDataRow()["Year"];
                        obMonth = view.GetFocusedDataRow()["Month"];
                    }
                    else
                    {
                        flag = false;
                        //if (frDView != null && !frDView.IsDisposed)
                        //    frDView.Select();
                        //else
                        //{
                            frDView = new FrmDeliveryView(Convert.ToInt32(view.GetFocusedDataRow()["DID"])) { MdiParent = this, Text = "ContNo: " + view.GetFocusedDataRow()["DID"].ToString() };
                            frDView.LoadData();
                            frDView.Show();
                            Savelayout(frDView.Text, ribbon.SelectedPage.Text,strDePlanning);
                       // }
                    }
                }
                if (flag == true)
                {
                    if (frDGaneral != null && !frDGaneral.IsDisposed)
                    {
                        frDGaneral.Select();
                        frDGaneral.LoadGeneral(obYear, obMonth);
                    }
                    else
                    {
                        frDGaneral = new FrmDeliveryGaneral();
                        frDGaneral.LoadGeneral(obYear,obMonth);
                        frDGaneral.MdiParent = this;
                        frDGaneral.Show();
                    }
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Delivery Update]
        private void Delivery_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New":
                    frDView = new FrmDeliveryView(-1) {MdiParent=this,Text="Add New Delivery"};
                    frDView.Show();
                    frDView.AddNew();
                    frDView.LoadData();
                    Savelayout(frDView.Text, ribbon.SelectedPage.Text, strDePlanning);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                    break;
                case "Save":
                    if (frDView != null && !frDView.IsDisposed)
                    {
                        frDView.UpdateData("Update");
                    }
                    if (ClassShare.frDV != null && !ClassShare.frDV.IsDisposed)
                        ClassShare.frDV.UpdateData("Update");
                    break;
                case "Delete":
                    if (frDView != null && !frDView.IsDisposed)
                    {
                        frDView.UpdateData("Delete");
                    }
                    sp_DeliveryMenuTableAdapter.Fill(dataSet_Delivery.sp_DeliveryMenu);
                    break;
                case "Refresh":
                    sp_DeliveryMenuTableAdapter.Fill(dataSet_Delivery.sp_DeliveryMenu);
                    if (frDView != null && !frDView.IsDisposed)
                    {
                        frDView.LoadData();
                    }
                    break;
                case "Preview":
                    if (frDGaneral != null && !frDGaneral.IsDisposed)
                    {
                        frDGaneral.Preview();
                    }
                    break;
                case "Inventory":
                    if (frInventory != null && !frInventory.IsDisposed)
                    {
                        frInventory.Select();
                        frInventory.LoadData();
                    }
                    else
                    {
                        frInventory = new FrmProductionInventory();
                        frInventory.MdiParent = this;
                        frInventory.LoadData();
                        frInventory.Show();
                    }
                    break;
            }
        }
        #endregion

        #region[Shipping]
        private void Invoice_ItemClick(object sender, ItemClickEventArgs e)
        {
            //switch (e.Item.Caption)
            //{
            //    case "New Invoice":
            //        frmInv = new FrmInvoice(-1) { MdiParent = this, Text = "New Invoice" };
            //        frmInv.AddNew();
            //        frmInv.LoadData();
            //        frmInv.Show();
            //        Savelayout(frmInv.Text, ribbon.SelectedPage.Text,strShipping);
            //        break;
            //    case "Save":
            //        if (frmInv != null && !frmInv.IsDisposed)
            //            frmInv.UpdateInvoice("Update");
            //        break;
            //    case "Delete":
            //        if (frmInv != null && !frmInv.IsDisposed)
            //            frmInv.UpdateInvoice("Delete");
            //        break;
            //    case "Refresh":
            //        if (frmInv != null && !frmInv.IsDisposed)
            //            frmInv.LoadData();
            //        break;
            //    case "Preview":
            //        if (frmInv != null && !frmInv.IsDisposed)
            //            frmInv.Preview();       
            //        break;
            //}
            //navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }
       

        private void gridView_InvMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view.GetRowLevel(view.FocusedRowHandle)==3)
                {
                    iSAID = Convert.ToInt32(view.GetFocusedDataRow()["SAID"]);                   
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["InvID"]) ? "" : view.GetFocusedDataRow()["InvID"].ToString()) != "")
                    {
                        iInvID = Convert.ToInt32(view.GetFocusedDataRow()["InvID"]);
                    }
                    else
                        iInvID = -1;
                    frmshipment = new FrmShipMent(iSAID,iInvID) { MdiParent = this, Text = view.GetFocusedDataRow()["Item"].ToString() };
                    frmshipment.LoadData();
                    frmshipment.Show();
                    Savelayout(frmshipment.Text, ribbon.SelectedPage.Text, strShipping);
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void newShippingAdviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ClassShare.ListDID.Clear();
                GridView view = gridView_InvMenu as GridView;
                int[] arDID = view.GetSelectedRows();
                foreach (int index in arDID)
                {
                    ClassShare.ListDID.Add(Convert.ToInt32(view.GetDataRow(index)["DID"]));                    
                }
                frmshipment = new FrmShipMent(-1,-1) { MdiParent = this, Text ="Add new shipping advice" };
                frmshipment.LoadData();
                frmshipment.Show();
                frmshipment.AddNewMaster();
                Savelayout(frmshipment.Text, ribbon.SelectedPage.Text, strShipping);
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Shipping_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ClassShare.iTabShippingIndex == 0)
            {
                switch (e.Item.Caption)
                {
                    case "Refresh":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.LoadData();
                            sp_SAMenuTableAdapter.Fill(dataSet_ShipMent.sp_SAMenu);
                        }
                        break;
                    case "Save":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.UpdateData("Update");
                        }
                        break;
                    case "Delete":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.UpdateData("Delete");
                        }
                        break;
                    case "Preview":
                        break;
                }
            }
            else
            {
                switch (e.Item.Caption)
                {
                    case "Refresh":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.RefreshInvoice();
                            sp_SAMenuTableAdapter.Fill(dataSet_ShipMent.sp_SAMenu);
                        }
                        break;
                    case "Save":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.UpdateInvoice("Update");
                        }
                        break;
                    case "Delete":
                        if (frmshipment != null && !frmshipment.IsDisposed)
                        {
                            frmshipment.UpdateInvoice("Delete");
                        }
                        break;
                    case "Preview":
                        break;
                }
            }
        }
        #endregion

        #region[Costing]
        private void gridView_StyleMenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;                
                    if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                    {
                        iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                        Cus = null;
                        frCGV = new FrmCostingGaneral(iYear, Cus) { MdiParent=this,Text="Style No: "+view.GetFocusedDataRow()["StyleNo"].ToString()};
                        frCGV.LoadData();
                        frCGV.Show();
                        Savelayout(frCGV.Text, ribbon.SelectedPage.Text,strCosting); 
                    }
                    else
                    {
                        if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                        {
                            Cus = view.GetFocusedDataRow()["Customer"];
                            iYear = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);                            
                            frCGV = new FrmCostingGaneral(iYear, Cus) { MdiParent = this, Text = "Style No: " + view.GetFocusedDataRow()["StyleNo"].ToString() };
                            frCGV.LoadData();
                            frCGV.Show();
                            Savelayout(frCGV.Text, ribbon.SelectedPage.Text, strCosting); 
                        }
                        else
                        {
                            CMID = Convert.ToInt32(view.GetFocusedDataRow()["CMID"]);
                            frCostD = new FrmCostingDetails(CMID) { MdiParent = this, Text = "Style No: " + view.GetFocusedDataRow()["styleNo"] };
                            frCostD.LoadData();
                            frCostD.Show();
                            Savelayout(frCostD.Text, ribbon.SelectedPage.Text, strCosting); 
                        }
                    }                   
                    navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                                               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void Costing_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New Cost":
                    frCostD = new FrmCostingDetails(-1) { MdiParent = this, Text = "Add new cost" };
                    frCostD.Show();
                    frCostD.AddNew();
                    frCostD.LoadData();
                    Savelayout(frCostD.Text, ribbon.SelectedPage.Text, strCosting);
                    break;
                case "Save":
                    if (frCostD != null && !frCostD.IsDisposed)
                    {
                        frCostD.UpdateCost("Update");
                    }
                    break;
                case "Delete":
                    if (frCostD != null && !frCostD.IsDisposed)
                    {
                        frCostD.UpdateCost("Delete");
                    }
                    sp_CostingMenuTableAdapter.Fill(dataSetOrderManagement.sp_CostingMenu);
                    break;                    
                case "Refresh":
                    sp_CostingMenuTableAdapter.Fill(dataSetOrderManagement.sp_CostingMenu);
                    if (frCostD != null && !frCostD.IsDisposed)
                    {
                        frCostD.LoadData();
                    }
                    break;
                case "Preview":
                    if (frCostD != null && !frCostD.IsDisposed)
                    {
                        frCostD.Preview();
                    }                    
                    break;
            }
            navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
        }
            #region[NewMA]
            private void bntCostingMA_ItemClick(object sender, ItemClickEventArgs e)
            {
                frMALib = new FrmMALibrary(-1);                
                frMALib.Text = "Add new Fabric Library";
                frMALib.Show();
                frMALib.AddNew();
                frMALib.LoadData();
                if (frCostD != null && !frCostD.IsDisposed)
                {
                    frCostD.RefreshMA();
                }     
               
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            private void bntCostingAC_ItemClick(object sender, ItemClickEventArgs e)
            {
                frMA = new FrmMaterial(-1);                
                frMA.Text = "Add new Accessories Library";
                frMA.Show();
                frMA.AddNew();
                frMA.LoadData();
                if (frCostD != null && !frCostD.IsDisposed)
                {
                    frCostD.RefreshMA();
                }     
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            #endregion            

            private void bnt_ProDelete_ItemClick(object sender, ItemClickEventArgs e)
            {

            }

        #endregion        
    }
}